package com.yishan.utils;

import com.alibaba.fastjson2.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yishan.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @description: jwt的工具类
 * @author:别纪元
 * @create:2024/1/5 17:11
 */
@Component
public class JwtUtils {

    private static final String security="deep";

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成token,将token存放到redis中
     * @param userName
     * @param passWord
     * @return
     */
    public  String createJWT(String userName, String passWord){
        //签发时间
        Date date = new Date();
        //获取时间搓
        Date expireDate = new Date(date.getTime() + 1000 * 60);
        HashMap<String, Object> map = new HashMap<>();
        map.put("alg","HS256");
        map.put("typ","JWT");
        String sign = JWT.create()
                .withHeader(map).withIssuer("deep")
                .withIssuedAt(date)
                .withExpiresAt(expireDate)
                .withClaim("userName", userName)
                .withClaim("passWord", passWord)
                .sign(Algorithm.HMAC256(security));
        User user = new User(userName, passWord);
        ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(sign, JSON.toJSONString(user),2, TimeUnit.MINUTES);
        return sign;
    }

    /**
     * jwt校验
     * @param token 传输token值
     * @return response token是否成功
     */
    public  boolean verifyToken(String token){
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(security)).build();
            DecodedJWT verify = jwtVerifier.verify(token);
            System.out.println("token校验正确");
            return true;
        } catch (Exception e) {
            System.out.println("token验证不正确");
            return false;
        }
    }


}
